package String;

import java.util.ArrayList;
import java.util.List;

public class _722_RemoveComments {

    public List<String> removeComments(String[] source) {
        if (source == null || source.length == 0) {
            return null;
        }
        List<String> results = new ArrayList<>();
        StringBuffer sb = new StringBuffer("");
        boolean blockComment = false;//distinguish with line comment and check if there are many blockComment
        boolean add  = true;
        for (String s : source) {
            char[] arr  = s.toCharArray();
            for (int i = 0; i < arr.length; i++) {
                if (add) {
                    sb.append(arr[i]);
                }
                if (i < arr.length - 1) {
                    if (!blockComment && arr[i] == '/' && arr[i + 1] == '/') {
                        sb.deleteCharAt(sb.length() - 1);
                        break;
                    }else if (!blockComment && arr[i] == '/' && arr[i+1] == '*') {
                        add = false;
                        sb.deleteCharAt(sb.length()-1);
                        blockComment = true;
                        i++;
                    } else if (blockComment && arr[i] =='*' && arr[i+1] =='/') {
                        add = true;
                        blockComment = false;
                        i++;
                    }
                }
            }
            if (add && sb.length() > 0) {
                results.add(sb.toString());
                sb = new StringBuffer("");
            }
        }
        return results;
    }

    public List<String> removeComments_F(String[] source) {
        List<String> results = new ArrayList<>();
        String tempS = "";
        boolean blockComment = false;
        for (String s:source) {
            System.out.println(s);
            if (s.indexOf("/*") != -1) {
                tempS += s.substring(0, s.indexOf("/*"));
                blockComment = true;
                if (s.indexOf("*/") != -1) {
                    tempS += s.substring(s.lastIndexOf("*/")+2,s.length());
                    if (!tempS.equals("")) {
                        results.add(tempS);
                    }
                    tempS = "";
                    blockComment = false;
                }
            }else if(s.indexOf("*/")!=-1) {
                tempS += s.substring(s.lastIndexOf("*/")+2,s.length());
                if (!tempS.equals("")) {
                    results.add(tempS);
                }
                tempS = "";
                blockComment = false;
            } else if (s.indexOf("//") != -1) {
                if (!blockComment) {
                    results.add(s.substring(0, s.indexOf("//")));
                }
            } else {
                if (!blockComment) {
                    results.add(s);
                }
            }
        }
        return results;
    }
}
